﻿using OpenCvSharp;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Point = OpenCvSharp.Point;
using Size = OpenCvSharp.Size;
using OpenCvSharp.Extensions;
using Common.plate.common;

namespace Common.plate.plateRecognizer
{
    // 全局变量：存储当前识别到的车牌号
    public static class GlobalData
    {
        public static string Plate { get; set; } = "";
    }

    /// <summary>
    /// 视频处理工具类
    /// </summary>
    public static class VideoProcessor
    {
        /// <summary>
        /// 处理视频文件或摄像头输入
        /// </summary>
        /// <param name="videoPath">视频路径（null则使用摄像头）</param>
        /// <param name="outputPath">输出视频路径</param>
        /// <param name="frameSkip">跳帧数</param>
        public static void ProcessVideo(string videoPath = null, string outputPath = "output.mp4", int frameSkip = 0)
        {
            // 初始化视频捕获（摄像头或文件）
            using (var capture = videoPath == null ? new VideoCapture(0) : new VideoCapture(videoPath))
            {
                if (!capture.IsOpened())
                {
                    Console.WriteLine("错误：无法打开视频源");
                    return;
                }

                // 获取视频属性（帧率、宽、高）
                double fps = capture.Fps;
                int width = (int)capture.FrameWidth;
                int height = (int)capture.FrameHeight;

                // 初始化视频写入器
                using (var writer = new VideoWriter(outputPath, FourCC.FromString("mp4v"), fps, new Size(width, height)))
                {
                    // 初始化车牌识别器
                    var plateRec = new PlateRecognizer();
                    Console.WriteLine($"开始处理视频，跳帧数: {frameSkip}，按'q'键退出...");

                    int frameCount = 0;
                    Mat frame = new Mat();

                    // 循环读取视频帧
                    while (true)
                    {
                        // 读取一帧图像
                        if (!capture.Read(frame))
                            break;

                        // 跳帧处理（每处理1帧跳过frameSkip帧）
                        
                        if (frameSkip > 0 && frameCount % (frameSkip + 1) != 0)
                        {
                            writer.Write(frame); // 写入原始帧
                            frameCount++;
                            continue;
                        }
                        frameCount++;

                        // 识别车牌
                        var plateObjs = plateRec.RecognizePlate(frame);

                        // 更新全局车牌变量（仅保留高置信度结果）
                        GlobalData.Plate = plateObjs.Any(p => p.ScoreText > 0.8f)
                            ? plateObjs.First(p => p.ScoreText > 0.8f).Text
                            : null;

                        // 绘制识别结果（边界框和文字）
                        ResultVisualizer resultVisualizer = new ResultVisualizer();
                        foreach (var obj in plateObjs.Where(p => p.ScoreText > 0.8f))
                        {
                            resultVisualizer.DrawDetectionWithChinese1(frame, obj);
                        }

                        // 显示处理后的帧
                        Cv2.ImShow("车牌识别", frame);
                        Console.WriteLine($"车牌号：{GlobalData.Plate}");
                        // 写入处理后的帧到输出视频
                        writer.Write(frame);

                        // 按'q'键退出
                        if (Cv2.WaitKey(1) == 27)
                            break;
                    }

                    // 释放资源
                    frame.Release();
                    Cv2.DestroyAllWindows();
                    Console.WriteLine($"处理完成，结果已保存到 {outputPath}");
                }
            }
        }
    }
}
